package com.bristua.barcode.common.util;


import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author hrt
 * @date 2018年1月4日
 * @description
 * 常用工具类
 */
public class Utils {



	/**
	 * @Description: 获取客户端IP地址
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1")) {
				//根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (Exception e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}
		// 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}



	/**
	 * 手机号码正则表达式
	 */
	private static final String PHONE_NUMBER_REG = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";

	/**
	 * 生成订单号时间戳+随机数组合
	 * @return
	 */
	public static String getOrdNo(){
		Random random = new Random();
		int x = random.nextInt(8999);
		int y = x + 1000;
		return DateUtils.getTimeStamp() + String.valueOf(y);
	}


	/**
	 * yyyyMMddHHmmssSSS+随机数组合
	 * @return  20位
	 */
	public static String genID(){
		Random random = new Random();
		int x = random.nextInt(899999);
		int y = x+100000;
		return (DateUtils.getDateTime()+ String.valueOf(y));
	}

	/**
	 * 相除
	 * @param obj 被除数，原有金额
	 * @param divisor 除数
	 * @return
	 */
	public static double divide(Object obj, int divisor){
		if(StringUtils.isEmpty(obj) || "0".equals(obj)){
			return 0;
		}
		BigDecimal bdAmt = new BigDecimal(String.valueOf(obj));
		BigDecimal bdAmt2 = new BigDecimal(String.valueOf(divisor));
		BigDecimal surplus= bdAmt.divide(bdAmt2);
		return surplus.doubleValue();
	}

	/**
	 * 相乘
	 * @param obj 被乘数，原有金额
	 * @param divisor 乘数
	 * @return
	 */
	public static double multiply(Object obj, int divisor){
		if(StringUtils.isEmpty(obj) || "0".equals(obj)){
			return 0;
		}
		BigDecimal bdAmt = new BigDecimal(String.valueOf(obj));
		BigDecimal bdAmt2 = new BigDecimal(String.valueOf(divisor));
		BigDecimal surplus= bdAmt.multiply(bdAmt2);
		return surplus.doubleValue();
	}


	/**
	 * 获取uuid
	 * @return
	 */
	public static String uuid(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 判断是否为手机号
	 * @param mobile
	 * @return
	 */
	public static boolean isMobile(String mobile){
        return valid(PHONE_NUMBER_REG, mobile);
	}

	/**
	 * 正则验证
	 * @param reg
	 * @param tmp
	 * @return
	 */
	public static boolean valid(String reg, String tmp){
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(tmp);
        return m.matches();
	}

	/**
	 * 获取请求流水
	 * @return
	 */
	public static String getRequestjournal(){
		return Long.toString(Math.abs(new Random().nextLong()));
	}

	/**
	 * 获取客户端真实IP
	 * @param request
	 * @return
	 */
	public static String getClientIp(HttpServletRequest request) {

		if (request == null)
			return null;
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("HTTP_CLIENT_IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();
		if(ip.indexOf(",") != -1){
			ip = ip.split(",")[0].toString() ;
		}
		if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)){
			try {
				ip = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
		return ip;
	}

	/**
	 * 判断是不是微信浏览器打开的
	 * @param request
	 * @return
	 */
	public static boolean isWxBrowser(HttpServletRequest request) {

		String userAgent = request.getHeader("user-agent").toLowerCase();
		return userAgent.contains("micromessenger");
	}

	/**
	 * 获取完整的应用部署路径：例如：http://www.yidianlife.cn/mobile
	 * @param request
	 * @return
	 */
	public static String getAppUrl(HttpServletRequest request) {
		String url = request.getScheme() + "://" + request.getServerName();
		if(request.getServerPort() != 80
				&& request.getServerPort() != 443){
			url += ":" + request.getServerPort();
		}
		url += request.getContextPath();
		return url;
	}

    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

	/**
	 * 1、移动号段有134，135，136，137, 138，139，147，150，151, 152，157，158，159，178，182，183，184，187，188。
	 * 2、联通号段有130，131，132，155，156，185，186，145，176。
	 * 3、电信号段有133，153，177，173，180，181，189。
	 */
	public static String YD = "^((134)|(135)|(136)|(137)|(138)|(139)|(147)|(148)|(150)|(151)|(152)|(157)|(158)|(159)|(172)|(178)|(182)|(183)|(184)|(187)|(188)|(198))\\d{8}$";
	public static String LT = "^((130)|(131)|(132)|(145)|(146)|(155)|(156)|(185)|(186)|(176)|(175)|(171)|(166))\\d{8}$";
	public static String DX = "^((133)|(149)|(153)|(173)|(177)|(180)|(181)|(189)|(199))\\d{8}$";

	public static String V_YD="^((1703)|(1705)|(1706))\\d{7}$";
	public static String V_LT="^((1707)|(1708)|(1709))\\d{7}$";
	public static String V_DX="^((1700)|(1701)|(1702))\\d{7}$";

	/**
	 * 获取运营商
	 * 0：移动、1：电信、2：联通、null：未知
	 * @param phone
	 * @return
	 */
	public static String getPhoneOperator(String phone) {
		if(StringUtils.isEmpty(phone))
			return null;

		// 判断手机号码是否是11位
		if (phone.length() == 11) {
			// 判断手机号码是否符合中国移动的号码规则
			if (phone.matches(YD)||phone.matches(V_YD)) {
				return "0";
			}
			// 判断手机号码是否符合中国联通的号码规则
			else if (phone.matches(LT)||phone.matches(V_LT)) {
				return "2";
			}
			// 判断手机号码是否符合中国电信的号码规则
			else if (phone.matches(DX)||phone.matches(V_DX)) {
				return "1";
			}
			// 都不合适 未知
			else {
				return null;
			}
		}
		// 不是11位
		else {
			return null;
		}
	}

	/***
	 * 字符串分割数组
	 * @param separator 分割符
	 * @param str 原字符串
	 * @return 字符串数组
	 */
	public  static String[]  strToArray(String separator,String str){
		if(StringUtils.isEmpty(separator)||StringUtils.isEmpty(str)){
			return null;
		}
		return str.split(separator);
	}
}
